<template>
  <span>
    <i v-if="type === 'icon'" class="el-icon-share" @click="open"></i>
    <el-button v-else plain :type="type" :size="size" icon="el-icon-share" class="share-btn" @click="open">
      分享
    </el-button>
    <el-dialog title="分享" append-to-body width="600px" :visible.sync="showDialog" class="avue-dialog share-dialog">
      <div class="form-wrapper">
        <ShareForm ref="form" :matrix-id="matrixId" :visible="showDialog" />
      </div>
      <div slot="footer" class="avue-dialog__footer avue-dialog__footer--right">
        <el-button size="small" @click="showDialog = false">取消</el-button>
        <el-button size="small" type="primary" :loading="submitting" @click="onSubmitClick">确定</el-button>
      </div>
    </el-dialog>
  </span>
</template>
<script>
import ShareForm from './share-form'
import { shareSave } from '@/api/chart/chart'

export default {
  components: { ShareForm },
  props: {
    size: { type: String, default: '' }, // 大小
    type: { type: String, default: 'default' }, // 类型
    matrixId: { type: String, default: '' }, // 指标ID
  },
  data() {
    return {
      showDialog: false,
      submitting: false,
    }
  },
  methods: {
    open() {
      this.showDialog = true
    },
    close() {
      this.submitting = false
      this.showDialog = false
    },
    stopExport() {
      this.submitting = false
    },
    onSubmitClick() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          done()
          const params = this.$refs.form.getValue()
          this.handleSubmit(params)
        } else {
          return false
        }
      })
    },
    async handleSubmit(params) {
      this.submitting = true
      try {
        const { success } = await shareSave({ matrixId: this.$route.params.id, ids: params.ids })
        if (success) {
          this.showDialog = false
          this.$message.success('已分享')
        } else {
          this.$message.error('分享失败，请稍后重试')
        }
      } catch (error) {
        console.log('handleSubmit error=', error)
        this.$message.error('分享失败，请稍后重试')
      }
      this.submitting = false
    },
  },
}
</script>
<style lang="scss" scoped>
.share-dialog {
  :deep(.el-dialog__body) {
    margin-bottom: 0;
  }

  .form-wrapper {
    .tips {
      margin: 16px 0 24px;
      color: #999;
    }
  }

  :deep(label[for='images']) {
    margin-left: 8px;
  }
}
</style>
